package com.bruce.zk;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;

/**
 * @author Bruce
 */
public class TestZookeeper {
    public static void main(String[] args) throws Exception {
        get();
    }

    public static void list() throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper("106.53.122.148:2181", 10000, watchedEvent -> {});
        listAll(zooKeeper, "/");
    }

    public static void get() throws Exception{
        ZooKeeper zooKeeper = new ZooKeeper("106.53.122.148:2181", 10000, watchedEvent -> {});
        byte[] data = zooKeeper.getData("/parent", false, null);
        System.out.println(new String(data));
    }

    public static void listAll(ZooKeeper zooKeeper, String path) throws InterruptedException, KeeperException {
        List<String> children = zooKeeper.getChildren(path, false);
        for (String child : children){
            String currentNodeName = "/".equals(path) ? (path + child) : (path + "/" + child);
            System.out.println(currentNodeName);
            listAll(zooKeeper, currentNodeName);
        }
    }




    public static void create() throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = new ZooKeeper("106.53.122.148:2181", 10000, watchedEvent -> System.out.println("watch方法执行"));
        System.out.println(zooKeeper.create("/parent", "parent data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT));
        System.out.println(zooKeeper.create("/parent/tmp", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL));
        System.out.println(zooKeeper.create("/parent/sequence", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL));
        Thread.sleep(6000);
        zooKeeper.close();
    }

}
